package com.fcai.microserv.jwt.interceptor;

import com.fcai.microserv.jwt.FcaiJwtTokenManager;
import com.fcai.microserv.jwt.FcaiSecurityChecker;
import com.fcai.microserv.jwt.JwtConst;
import com.fcai.microserv.model.CommonRespCode;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 身份认证拦截器，拦截所有需授权的请求
 */
@Component
public class AuthenticationInterceptor extends AbstractFcaiSecurityInterceptor {

    private FcaiJwtTokenManager tokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }

        FcaiSecurityChecker requestVerify = super.findSecurityCheckAnnotation((HandlerMethod) handler);
        if (requestVerify == null || !requestVerify.check()) {
            // 不需要身份验证，直接返回
            return true;
        }

        Object user = request.getAttribute(JwtConst.CURRENT_USER_ID_HTTP_ATTR);
        if (user == null) {
            responseError(response, CommonRespCode.AUTH_FAIL);
            return false;
        }

//        String tokenType = request.getAttribute(JwtConst.CURRENT_USER_TYPE_HTTP_ATTR).toString();
//        if (StringUtils.equals(tokenType, SysConst.TOKEN_TYPE_ADMIN)) {
//            if (StringUtils.startsWith(request.getRequestURI(), "/admin/")) {
//                return true;
//            }
//        }
//
//        if (StringUtils.equals(tokenType, SysConst.TOKEN_TYPE_USER)) {
//            if (StringUtils.startsWith(request.getRequestURI(), "/api/")) {
//                return true;
//            }
//        }
        // 默认返回令牌有误
        responseError(response, CommonRespCode.AUTH_FAIL);
        return false;
    }

}
